/**
 * 新增修改完成调用 modalFormOk方法 编辑弹框组件ref定义为modalForm
 * 高级查询按钮调用 superQuery方法  高级查询组件ref定义为superQueryModal
 * data中url定义 list为查询列表  delete为删除单条记录  deleteBatch为批量删除
 */
import { filterObj } from '@/utils/util'
import { deleteAction, getAction, downFile, getFileAccessHttpUrl, postAction } from '@/services/manage'
import Criteria from '@/utils/criteria'
import { OPERATOR } from '@/store/mutation-types'
export const VxeTableMixin = {
  data() {
    return {
      queryParam: {},
      tableToolbar: {
        refresh: {
          query: () => {
            this.onClearSelected()
            this.loadData(1)
          }
        },
        import: true,
        buttons: [
          { buttonRender: { name: 'VxeToolbarAdd', events: { click: this.handleAdd }}},
          { buttonRender: { name: 'VxeToolbarBatchDel', events: { click: this.batchDel }}}
        ],
        tools: [],
        perfect: true,
        export: false,
        print: false,
        zoom: true,
        custom: true,
        slots: { },
        'class-name': 'z-vxe-toolbar'
      },
      height: 400,
      /* 数据源 */
      dataSource: [],
      /* 分页参数 */
      ipagination: {
        total: 0,
        currentPage: 1,
        pageSize: 10
      },
      /* 排序参数 */
      isorter: {
        fieldName: 'createTime',
        desc: true
      },
      /* 筛选参数 */
      filters: {},
      /* table加载状态 */
      loading: false,
      /* table选中keys*/
      selectedRowKeys: [],
      /* table选中records*/
      selectionRows: [],
      /* 查询折叠 */
      toggleSearchStatus: false,
      /* 高级查询条件生效状态 */
      superQueryFlag: false,
      /* 高级查询条件 */
      superQueryParams: '',
      /** 高级查询拼接方式 */
      superQueryMatchType: 'and',
      labelCol: { span: 5 },
      wrapperCol: { span: 18 },
      listeners: {
        'sort-change': this.sortChange,
        'checkbox-change': this.onSelectChange,
        'checkbox-all': this.onSelectChange,
        'page-change': this.handlePageChange
      },
      categoryData: {} // 页面资源类别数据
    }
  },
  created() {
    if (!this.disableMixinCreated) {
      this.loadData()
    }
    !this.disableMixinCreatedCategory && this.getPageCategory()
  },
  mounted() {
    setTimeout(() => {
      this.setTableHeight()
    }, 100)
  },
  computed: {
    options() {
      /*
      *customTableToolbar为页面需要自定义的toolbar配置
      *也可以直接在页面组件使用时直接定义属性覆盖该配置
      */
      const toolbarConfig = Object.assign({}, this.tableToolbar, this.customTableToolbar)
      return {
        customConfig: { storage: { visible: true, resizable: true }},
        rowConfig: { keyField: 'id' },
        loading: this.loading,
        height: this.height,
        toolbarConfig: toolbarConfig,
        columns: this.columns || [],
        data: this.dataSource || [],
        pagerConfig: {
          ...this.ipagination,
          layouts: ['Sizes', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'FullJump', 'PageCount', 'Total']
        },
        sortConfig: { trigger: 'cell', remote: true },
        exportConfig: {
          remote: true,
          exportMethod: ({ options }) => {
            this.handleExportXls(options.filename)
          }
        },
        importConfig: {
          remote: true,
          types: ['xls', 'xlsx'],
          importMethod: ({ file, options }) => {
            this.handleImportXls({ file, options })
          }
        }
      }
    }
  },
  methods: {
    loadData(arg) {
      if (!this.url.list) {
        this.$message.error('请设置url.list属性!')
        return
      }
      // 加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.currentPage = 1
      }
      var params = this.getQueryParams()// 查询条件
      this.loading = true
      return getAction(this.url.list, params).then((res) => {
        if (res.success) {
          this.dataSource = res.result.content || res.result
          this.ipagination.total = res.result.totalElements
        }
        // else {
        //   this.$message.warning(res.message)
        // }
        this.loading = false
      })
    },
    handleSuperQuery(params, matchType) {
      // 高级查询方法
      if (!params) {
        this.superQueryParams = ''
        this.superQueryFlag = false
      } else {
        this.superQueryFlag = true
        this.superQueryParams = JSON.stringify(params)
        this.superQueryMatchType = matchType
      }
      this.onClearSelected()
      this.loadData(1)
    },
    getQueryParams() {
      // 获取查询条件
      const sqp = {}
      if (this.superQueryParams) {
        sqp['superQueryParams'] = encodeURI(this.superQueryParams)
        sqp['superQueryMatchType'] = this.superQueryMatchType
      }
      // var param = Object.assign(sqp, this.queryParam, this.isorter, this.filters)
      const queryParam = new Criteria()
      queryParam.addCriterions(Object.assign({}, this.queryParam, this.filters), OPERATOR.LIKE_START)
      this.isorter && queryParam.addOrder(this.isorter)
      var param = Object.assign(sqp, { criteria: queryParam.getEncode() })
      param.field = this.getQueryField()
      param.pageNo = this.ipagination.currentPage
      param.pageSize = this.ipagination.pageSize
      return filterObj(param)
    },
    getQueryField() {
      // TODO 字段权限控制
      var str = 'id,'
      this.columns.forEach(function(value) {
        if (value.field) {
          str += ',' + value.field
        }
      })
      return str
    },
    onSelectChange({ records }) {
      this.selectedRowKeys = []
      records.forEach(item => {
        const rowId = this.$refs.vxeTable.getRowid(item)
        this.selectedRowKeys.push(rowId)
      })
      this.selectionRows = records
    },
    onClearSelected() {
      this.selectedRowKeys = []
      this.selectionRows = []
    },
    searchQuery() {
      this.onClearSelected()
      this.loadData(1)
    },
    superQuery() {
      this.$refs.superQueryModal.show()
    },
    searchReset() {
      this.onClearSelected()
      this.queryParam = {}
      this.loadData(1)
    },
    async batchDel() {
      if (!this.url.deleteBatch) {
        this.$message.error('请设置url.deleteBatch属性!')
        return
      }
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！')
        return
      } else {
        if (typeof this.batchDelBefore === 'function') {
          // 批量删除之前执行判断，是否能删除,支持异步
          const message = await this.batchDelBefore()
          if (message) {
            return this.$message.warning(message)
          }
        }
        this.$confirm({
          title: '确认删除',
          content: '是否删除选中数据?',
          onOk: () => {
            this.loading = true
            deleteAction(`${this.url.deleteBatch}${this.selectedRowKeys.join()}`).then((res) => {
              if (res.success) {
                this.$message.success(res.message)
                this.loadData()
                this.onClearSelected()
              }
              // else {
              //   this.$message.warning(res.message)
              // }
            }).finally(() => {
              this.loading = false
            })
          }
        })
      }
    },
    async handleDelete(id) {
      if (!this.url.delete) {
        this.$message.error('请设置url.delete属性!')
        return
      }
      if (typeof this.deleteBefore === 'function') {
        // 批量删除之前执行判断，是否能删除,支持异步
        const message = await this.deleteBefore()
        if (message) {
          return this.$message.warning(message)
        }
      }
      deleteAction(`${this.url.delete}${id}`).then((res) => {
        if (res.success) {
          this.$message.success(res.message)
          this.loadData()
        }
        // else {
        // this.$message.warning(res.message)
        // }
      })
    },
    async handleEdit(record) {
      if (typeof this.editBefore === 'function') {
        // 批量删除之前执行判断，是否能删除,支持异步
        const message = await this.editBefore()
        if (message) {
          return this.$message.warning(message)
        }
      }
      this.$refs.modalForm.edit({ ...record })
      this.$refs.modalForm.title = '编辑'
      this.$refs.modalForm.disableSubmit = false
    },
    handleAdd: function() {
      this.$refs.modalForm.add()
      this.$refs.modalForm.title = '新增'
      this.$refs.modalForm.disableSubmit = false
    },
    handleToggleSearch() {
      this.toggleSearchStatus = !this.toggleSearchStatus
    },
    // 给popup查询使用(查询区域不支持回填多个字段，限制只返回一个字段)
    getPopupField(fields) {
      return fields.split(',')[0]
    },
    modalFormOk() {
      // 新增/修改 成功时，重载列表
      this.loadData()
    },
    handleDetail: function(record) {
      this.$refs.modalForm.disableSubmit = true
      this.$refs.modalForm.edit(record)
      this.$refs.modalForm.title = '详情'
    },
    getPageCategory() { // 请求页面资源类别数据
      if (this.url && this.url.category) {
        getAction(this.url.category).then(res => {
          if (res.success) {
            this.categoryData = res.result || {}
          }
        })
      }
    },
    handleExportXls(fileName) {
      if (!fileName || typeof fileName !== 'string') {
        fileName = '导出文件'
      }
      const param = { ...this.queryParam }
      if (this.selectedRowKeys && this.selectedRowKeys.length > 0) {
        param['selections'] = this.selectedRowKeys.join(',')
      }
      downFile(this.url.exportXlsUrl, param).then((data) => {
        if (!data) {
          this.$message.warning('文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xls')
        } else {
          const url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          const link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) // 下载完成移除元素
          window.URL.revokeObjectURL(url) // 释放掉blob对象
        }
      })
    },
    handleImportXls({ file, options }) { // 页面表格导入
      if (Object.keys(this.categoryData).length <= 0 || !this.categoryData.importTemplate) {
        this.$message.warning('未查询到导入接口')
        return
      }
      const closeMessage = this.$message.loading('上传中..')
      const formData = new FormData()
      formData.append('file', file)
      postAction(`/excel/import/upload/${this.categoryData.importTemplate}`, formData).then(res => {
        closeMessage()
        if (res.success) {
          this.loadData()
          this.$message.success(res.message)
        }
      })
    },
    /* 图片预览 */
    getImgView(text) {
      if (text && text.indexOf(',') > 0) {
        text = text.substring(0, text.indexOf(','))
      }
      return getFileAccessHttpUrl(text)
    },
    /* 文件下载 */
    // update--autor:lvdandan-----date:20200630------for：修改下载文件方法名uploadFile改为downloadFile------
    downloadFile(text) {
      if (!text) {
        this.$message.warning('未知的文件')
        return
      }
      if (text.indexOf(',') > 0) {
        text = text.substring(0, text.indexOf(','))
      }
      const url = getFileAccessHttpUrl(text)
      window.open(url)
    },
    handlePageChange({ currentPage, pageSize }) {
      this.ipagination.currentPage = currentPage
      this.ipagination.pageSize = pageSize
      this.loadData()
    },
    setTableHeight() { // 设置页面表格高度
      if (this.$refs.vxeTable) {
        const clientHeight = document.documentElement.clientHeight
        const tableTop = this.$refs.vxeTable.$el.getBoundingClientRect().top
        this.height = clientHeight - tableTop - 40
      }
    },
    sortChange({ property, order }) { // 页面表格排序
      this.isorter = {
        fieldName: property,
        desc: order === 'desc'
      }
      this.loadData()
    }
  }

}
